import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wufei
 * @date 2018/3/14/014 15:31
 */
public class CuratorUtils {

    public static CuratorFramework getInstance(){
        return GetCuratorFramework.curatorFramework;
    }

    public static void main(String[] args) throws Exception {
       CuratorUtils.test();
    }

    public static void test() throws Exception {
        CuratorFramework curatorFramework = getInstance();
        curatorFramework.start();
        Stat stat = curatorFramework.checkExists().forPath("/curator");
        if (stat == null){
            curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/curator","123".getBytes());

        }else {
            System.out.println("已存在节点");
        }

        curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/curator/n1","123".getBytes());

        byte[] curators = curatorFramework.getData().forPath("/curator/n1");
        System.out.println(new String(curators));

        curatorFramework.setData().forPath("/curator/n1","234".getBytes());

        curators = curatorFramework.getData().forPath("/curator");
        System.out.println(new String(curators));

        curatorFramework.delete().forPath("/curator/n1");

        ExecutorService service = Executors.newFixedThreadPool(1);


        final CountDownLatch count = new CountDownLatch(1);
        curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).inBackground(new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                System.out.printf(Thread.currentThread().getName()+"->result:"+curatorEvent.getResultCode()+"-"+curatorEvent.getType());
                count.countDown();
            }
        },service).forPath("/curator/n1","123".getBytes());

        count.await();
        service.shutdown();

        curatorFramework.delete().forPath("/curator/n1");


    }
}

class GetCuratorFramework{

    private final static String CONNECTION = "111.231.119.251:2181,111.231.119.251:2182,111.231.119.251:2183";

    public static CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(CONNECTION,1000,3000,new RetryNTimes(3,1000));
}
